package com.artifex.mupdf.viewer

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.artifex.mupdf.viewer.databinding.ItemBookBinding

class BookAdapter(
    private val onItemClick: (Book) -> Unit,
    private val onMenuClick: (View, Book, Int) -> Unit
) : ListAdapter<Book, BookAdapter.ViewHolder>(DiffCallback()) {

    class ViewHolder(val binding: ItemBookBinding) : RecyclerView.ViewHolder(binding.root)

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val binding = ItemBookBinding.inflate(
            LayoutInflater.from(parent.context), parent, false
        )
        return ViewHolder(binding)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val item = getItem(position)

        with(holder.binding) {
            bookTitle.text = item.title
            bookAuthor.text = item.author ?: "Unknown Author"

            // Click listeners
            root.setOnClickListener { onItemClick(item) }
            bookCover.setOnClickListener { onMenuClick(it, item, position) }
        }
    }

    class DiffCallback : DiffUtil.ItemCallback<Book>() {
        override fun areItemsTheSame(oldItem: Book, newItem: Book) =
            oldItem.id == newItem.id

        override fun areContentsTheSame(oldItem: Book, newItem: Book) =
            oldItem == newItem
    }
}